package cn.hzc.fortess.system.page;

import cn.hzc.fortess.core.common.HttpContext;


import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PaginationParam implements Serializable {

    final private static Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");

    private Integer pageNo = Integer.parseInt(getRequestParam("page", 1));

    private Integer pageSize = Integer.parseInt(getRequestParam("limit", 20));

    private String order = "desc";

    private Integer limit = Integer.MAX_VALUE;

    private Long offset = 0L;

    private String sort = "id";


    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }


    public void setSort(String sort) {
        this.sort = sort;
    }

    public Integer getLimit() {
        return this.pageSize;
    }


    public Long getOffset() {
        return Long.valueOf((pageNo - 1) * pageSize);
    }


    public String getSort() {
        return camel2Underline(sort).toLowerCase();
    }


    private String getRequestParam(String paramName, Object defaultVal) {
        String val = HttpContext.getRequest().getParameter(paramName);
        if (val == null) {
            return defaultVal.toString();
        }
        return val;
    }

    private static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuilder sb = new StringBuilder();
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }

}
